package it.managerService;


import it.Dao.UserbookDao;
import it.domain.UBPageBean;
import it.domain.Userbook;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author wsx
 * @create 2020-04-22-10:50
 */
@WebServlet("/returnbooks")
public class returnbooks extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String currentPages = req.getParameter("currentPage");
        String query = req.getParameter("query");
        if (currentPages == null || "".equals(currentPages)) {
            currentPages = "1";
        }
        Integer currentPage = Integer.valueOf(currentPages);
        //防止点上一页时越界
        if (currentPage <= 1) {
            currentPage = 1;
        }
        UBPageBean ubPageBean = new UBPageBean();
        UserbookDao userbookDao = new UserbookDao();
        Long totalCount = null;
        if (query == null) {
            try {
                totalCount = userbookDao.getUBTotalCount();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            try {
                totalCount = userbookDao.getUBTotalCountByName(query);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //总记录数
        ubPageBean.setTotalCount(totalCount.intValue());
        //每页的记录数
        Integer counts = 8;
        //总页数
        double totalPage = Math.ceil(1.0 * ubPageBean.getTotalCount() / counts);
        if (currentPage >= (int) totalPage) {
            currentPage = (int) totalPage;
        }
        ubPageBean.setCurrPage(currentPage);
        ubPageBean.setTotalPage((int) totalPage);
        List<Userbook> list = null;
        if (query == null) {
            try {
                list = userbookDao.getUBAllList(currentPage, counts);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            try {
                list = userbookDao.getUBList(query, currentPage, counts);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        for (Object objct :list){
            System.out.println(objct);
        }
        ubPageBean.setBooksList(list);
        req.setAttribute("query",query);
        req.setAttribute("ubPageBean", ubPageBean);
//        req.getRequestDispatcher("manager_return.jsp").forward(req, resp);
    }
}
